"use strict"

module.exports = function(options) {
	let _ = require("lodash"),
		log4js = require('log4js'),
		logger = log4js.getLogger('qywx-api'),
		QywxAPI = require("../utils/QywxAPI")(),
		debug = require('debug')('qywx-api');

	return {
		get: function(dbCon, corpId, group, secret, cb) {
			dbCon.connect(function(err, db) {
				db.model("AccessToken")
					.findOne({
						corpId: corpId,
						group: group
					})
					.then(function(data) {
						debug(" find token from db : ", data);

						if (!data || data.tokenExpired) {
							//try to refresh token, before next step
							QywxAPI.getAccessToken(corpId, secret, function(err, data) {
								if (err) {
									return cb(err);
								}

								let accessToken = data.access_token;
								let expiresIn = data.expires_in; //In seconds

								//Save accesstoken into AccessToken db collection
								db.model("AccessToken")
									.update({
											corpId: corpId,
											group: group
										}, {
											corpId: corpId,
											group: group,
											token: accessToken,
											expiresAt: _.now() + (expiresIn - 3) * 1000
										}, {
											upsert: true
										},
										function(err) {
											if (err) {
												logger.error(err);
											}
										});
								return cb(null, accessToken, false);
							});
						} else {
							debug("token reuse from db");
							return cb(null, data.token, true)
						}
					})
					.catch(function(err) {
						logger.error(err);
						return cb(err);
					});
			});
		}
	}
}